package com.caipiao.lottery.lty.handler.impl;

import com.caipiao.lottery.cache.MemCacheManager;
import com.caipiao.lottery.config.Config;
import com.caipiao.lottery.data.UserCookie;
import com.caipiao.lottery.data.UserInfo;
import com.caipiao.lottery.dbwarpper.P_API_USER;
import com.caipiao.lottery.log.TraceLogger;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Screen;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2016/11/20.
 */
public class CookieManager {
    private static CookieManager instance = new CookieManager();
    boolean init_flag =false;
    public static boolean canCreateDriver = true;

    public static Map<String, UserThrea> map = new HashMap<String, UserThrea>();
    public static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    private CookieManager(){}

    public static CookieManager Instance()
    {
        return instance;
    }

    public static synchronized boolean lockDriver(){
        if(canCreateDriver){
            canCreateDriver = false;
            return true;
        }
        return false;
    }

    public static synchronized boolean freeDriver(){
        canCreateDriver = true;
        return true;
    }

    public void sendMess(String msgId, UserInfo user, String url, List<String> mess){
        UserThrea userThread = map.get(user.id);
        if(null == userThread || "TERMINATED".equalsIgnoreCase(userThread.getState().toString())){
            userThread = new UserThrea(user);
            userThread.start();
//            cachedThreadPool.execute(userThread);
            map.put(user.id, userThread);
        }
        userThread.sendMess(msgId, url, mess);
    }

    public static void main(String[] args) {
//        File file = new File("D:\\YunPan\\WorkCode\\idea_workspace\\AndroidSimulatorTestHttpPost1\\chromedriver.exe");
//        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());

//        System.setProperty("webdriver.chrome.driver", "D:\\YunPan\\WorkCode\\idea_workspace\\AndroidSimulatorTestHttpPost1\\chromedriver.exe");
//        System.setProperty("webdriver.chrome.bin", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
//        WebDriver driver = new ChromeDriver();
//
//        WebDriver test = new ChromeDriver();
//        test.get("http:www.baidu.com");
//        System.out.println(test.getTitle());
//        System.out.println("test.manage().window().getSize():" + test.manage().window().getSize());

//        test.manage().window().maximize();
//        test.manage().window().setSize(new Dimension(100, 100));
//        System.out.println("1234".substring(0, 1));


//        File file = new File("C:/Selenium/iexploredriver.exe");
//        System.setProperty("webdriver.ie.driver", file.getAbsolutePath());

        System.setProperty("webdriver.ie.driver", "D:\\YunPan\\WorkCode\\idea_workspace\\AndroidSimulatorTestHttpPost1\\iedriver64.exe");

        WebDriver test = new InternetExplorerDriver();
        test.get("http://www.baidu.com");



    }

}

class UserThrea extends Thread{
    private String msgId = "";
    public UserInfo userInfo = null;
    //发送弹幕的地址
    private String url = "";
    private List<String> mess = new ArrayList<String>();
    private String lastTime = "";
    private List<String> cookieList = new ArrayList<String>();
//    private ChromeOptions options = null;

    public UserThrea(UserInfo userInfo){
        this.userInfo = userInfo;

        File file = new File(Config.Init.GetPropValue("chromeDriverFilePath"));
        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
        //设置chrome执行文件
//        options = new ChromeOptions();
//        options.setBinary(Config.Init.GetPropValue("chromeFilePath"));
//        ChromeDriver driver = new ChromeDriver(options);

//        ChromeDriver driver = new ChromeDriver();


//        driver.manage().window().setSize(new Dimension(1424, 998));
//        driver.get("http://baidu.com");


    }

    public void sendMess(String msgId, String url, List<String> mess){
        this.url = url;
        this.mess.addAll(mess);
        this.msgId = msgId;
    }

    @Override
    public void run() {
        //查询用户所用的cookie列表
        List< UserCookie > cookieList = new ArrayList<UserCookie>();
        List<DriverCookie> dcList = new ArrayList<DriverCookie>();
        boolean db_r = P_API_USER.prGetCookieList("100101", userInfo,
                cookieList);
        TraceLogger.LtyBin.debug(msgId + "-Get userCookieList [user:" + userInfo.id + "] ");

        if (!db_r) {
            TraceLogger.LtyBin.debug(msgId + "-Get userCookieList [user:"+userInfo.id+"], run P_API_USER.prGetCookieList fiald ");
        }
        TraceLogger.LtyBin.debug(msgId + "-Get userCookieList [user:" + userInfo.id + "], success! count:" + cookieList.size());

        try {
            //实际用户获取的cookie数量
            int realCookieCount = cookieList.size();

            //创建driver窗口加锁
            for(int lo = 0; lo < 100; lo++){
                if(CookieManager.lockDriver()){
                   break;
                }
                Thread.sleep(1000);
            }

            for(int co = 0; co<realCookieCount; co++){
//                WebDriver driver = new ChromeDriver(options);
                WebDriver driver = new ChromeDriver();
//                driver.navigate().to(url);
                driver.get(url);

                //判断页面打开是否正常
                Screen s=new Screen();
                String pauseImg = Config.Init.GetPropValue("pauseImgPath");
                for(int pau=0; pau <40; pau++){
                    Thread.sleep(5000);
                    try {
                        s.find(pauseImg);
                        break;
                    } catch (FindFailed findFailed) {
                        //未找到暂停按钮
                        System.out.println("|| || || ==>> open Url pauseImg not found");
                        //如果找不到暂停按钮刷新页面
                        driver.navigate().refresh();
                    }
                }

                //获取发送的cookie
                driver.manage().deleteAllCookies();
                UserCookie userCookie = cookieList.get(co);
                String[] coArr = userCookie.cookie.split(";");
                for (String kv : coArr) {
                    Cookie cookie = new Cookie(kv.split("=")[0], kv.split("=", -1)[1]);
                    driver.manage().addCookie(cookie);
                }
                driver.navigate().refresh();

                //判断页面打开是否正常
                Screen s2=new Screen();
                String pauseImg2 = Config.Init.GetPropValue("pauseImgPath");
                for(int pau=0; pau <40; pau++){
                    Thread.sleep(5000);
                    try {
                        s2.find(pauseImg2);
                        break;
                    } catch (FindFailed findFailed) {
                        //未找到暂停按钮
                        System.out.println("|| || || ==>> open Url pauseImg not found");
                        //如果找不到暂停按钮刷新页面
                        driver.navigate().refresh();
                    }
                }

//                driver.manage().window().maximize();
                //设置窗口大小
//                driver.manage().window().setSize( new Dimension(1600,860));
                //暂停播放
                Screen s3=new Screen();
                String pauseImg3 = Config.Init.GetPropValue("pauseImgPath");
                for(int pau=0; pau <40; pau++){
                    try {
                        s3.find(pauseImg3);
                        s3.click(pauseImg3);
                        break;
                    } catch (FindFailed findFailed) {
                        //未找到暂停按钮
                        System.out.println("|| || || ==>> pauseImg not found");
                        //如果一直找不到暂停按钮，没0秒刷新页面
                        if(pau%10 == 9){
                            driver.navigate().refresh();
                            System.out.println("|| || || ==>> pauseImg not found, driver.refresh");
                        }
                        Thread.sleep(1000);
                    }
                }
                //最小化窗口
//                driver.manage().window().setSize( new Dimension(100,100));

                dcList.add(new DriverCookie(driver, userCookie));
            }

            //创建窗口完毕后，恢复锁
            CookieManager.freeDriver();

            ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

            //浏览器等待时间，等待多久后关闭
            //500毫秒执行一次
            int maxWaitMin = Integer.parseInt(Config.Init.GetPropValue("maxWaitMin"));
            for(int i = 0; i < maxWaitMin*60*2; i++){
                if(!mess.isEmpty() && 0 < mess.size()){
                    int messCount = mess.size();
                    for(int m = 0; m < messCount; m ++){
                        String sendMess = mess.get(0);
                        //消息内随机加空格
                        sendMess = sendMess.substring(0, (m%sendMess.length())) + " "
                                    +sendMess.substring((m%sendMess.length()), sendMess.length());

                        if(m%realCookieCount == 0 && 0 < m){
                            System.out.println("wait 6 second +++++==>>"+m);
                            Thread.sleep(6000);
                        }

                        cachedThreadPool.execute(new SendThread(msgId, dcList.get(m%realCookieCount),
                                userInfo, sendMess));

                        mess.remove(0);
                        //重置计数器
                        i = 0;
                    }

                    System.out.println("send finish clear Cache!!!!!!");
                    //添加完后解除缓存
                    MemCacheManager.Instance().common_cache.RemoveData(userInfo.id);
                }

                System.out.println("wait ===>>"+i);
                Thread.sleep(500);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //逐个关闭窗口
        for(DriverCookie dc :dcList){
            dc.driver.close();
            //修改cookie状态
            db_r = P_API_USER.freeCookie(msgId, dc.userCookie.id);
            TraceLogger.LtyBin.debug(msgId + "- free cookie [id:" + dc.userCookie.id + "] ");

            if (!db_r) {
                TraceLogger.LtyBin.debug(msgId + "- free cookie [id:" + dc.userCookie.id + "] fiald");
            }
            TraceLogger.LtyBin.debug(msgId + "- free cookie [id:" + dc.userCookie.id + "] SUCCESS");
        }

        //修改用户在线状态为不在线
        db_r = P_API_USER.updateUserOnlineStatus(msgId, userInfo.id, "0");

        if (!db_r) {
            TraceLogger.LtyBin.debug(msgId + "- 修改用户在线状态为不在线 fiald");
        }
        TraceLogger.LtyBin.debug(msgId + "- 修改用户在线状态为不在线 Success");

        System.out.println("closed!");
    }


}

class SendThread implements Runnable{
    private String msgId = "";
    private DriverCookie dc;
    private UserInfo userInfo;
    private String sendMess;

    public SendThread(String msgId, DriverCookie dc, UserInfo userInfo, String sendMess){
        this.msgId = msgId;
        this.dc = dc;
        this.userInfo = userInfo;
        this.sendMess = sendMess;
    }

    @Override
    public void run() {
        //输入内容，点击发送
        try {
            if("huya".equalsIgnoreCase(userInfo.pingtaiType)){
                System.out.println("begin send HuYa mess===>>"+sendMess);
                //虎牙发布
                sendHuya(dc.driver, sendMess);
            } else if("douyu".equalsIgnoreCase(userInfo.pingtaiType)){
                System.out.println("begin send DouYu mess===>>"+sendMess);
                //斗鱼发布
                sendDouyu(dc.driver, sendMess);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        String lastRunTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //发送成功，修改cookie最后运行时间
        boolean db_r = P_API_USER.updateCookieLastRunTime(msgId, dc.userCookie.id,
                lastRunTime);

        if (!db_r) {
            TraceLogger.LtyBin.debug(msgId + "- run updateCookieLastRunTime fiald!!");
        }
        TraceLogger.LtyBin.debug(msgId + "-update last run time [id:"+dc.userCookie.id+","+lastRunTime+"] success!");

    }

    private void sendHuya(WebDriver driver, String mess) throws Exception{
        WebElement context = driver.findElement(By.id("pub_msg_input"));
        context.sendKeys(" ");
        Thread.sleep(200);
        if(mess.length() > 30){
            context.sendKeys(mess.substring(0,30));
        } else {
            context.sendKeys(mess);
        }
        Thread.sleep(200);
        WebElement sendBtn = driver.findElement(By.id("msg_send_bt"));
        sendBtn.click();
        System.out.println(">>>" + mess);
        Thread.sleep(100);
    }


    private void sendDouyu(WebDriver driver, String mess) throws Exception{
        WebElement context = driver.findElement(By.className("cs-textarea"));
        context.sendKeys(" ");
//        Thread.sleep(2500);
        if(mess.length() > 20){
            context.sendKeys(mess.substring(0,20));
        } else {
            context.sendKeys(mess);
        }
//        Thread.sleep(100);
        WebElement sendBtn = driver.findElement(By.className("b-btn"));
//        WebElement sendBtn = driver.findElement(By.xpath("//DIV[@id='js-send-msg']/div"));
        sendBtn.click();
        System.out.println(">>>" + mess);
//        Thread.sleep(100);
    }
}

class DriverCookie{
    public WebDriver driver;
    public UserCookie userCookie;

    public DriverCookie(WebDriver driver, UserCookie userCookie){
        this.driver = driver;
        this.userCookie = userCookie;
    }
}























